<?

# Import the application settings.
require_once(dirname(__FILE__) . '/../config.php');

# Import the HMAC hash generation utility.
require_once(APPLICATION_ROOT . '/includes/HMAC.php');

# Import the database connection script.
require_once(APPLICATION_ROOT . '/db.php');

function listPurchases($id) {
	# Import the products.
	include(APPLICATION_ROOT . '/items.php');

	$id = mysql_escape_string(filter_var($id, FILTER_SANITIZE_STRING));

	$sql = new mod_db();
	$sql->connection();
	$query = $sql->query("SELECT * FROM " . BSDDS_PURCHASE_TABLE . " WHERE buyer_id = '{$id}' ORDER BY transactionID DESC");
	$info = mysql_fetch_array($query);

	if (!$info) {
		return FALSE;
	}

	echo "<table border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"4\"><tr bgcolor=\"#eeeeee\"><td>Item</td><td>Format</td><td>Status</td><td>Date</td><td>Download</td>";
	$i = 0;
	while ($info) {

		if ($i/2 == round($i/2)) {
			$which = NULL;
		} else {
			$which = 'style="background-color: #EBF3FF;"';
		}

		$i++;
		$date = htmlentities(date("m-d-y", strtotime($info['transaction_time'])));

		if (time() < (strtotime($info['time']) + BSDDS_LINK_EXPIRY)) { # Make secure URL.
			# Cobble together the URL here.

			if ($products[$info['itemID']]['location']) {
				#print_r($products[$info['itemID']['location']]);
				$userid = filter_input(INPUT_GET, 'userid', FILTER_SANITIZE_STRING);
				$filepath = $products[$info['itemID']]['location'] .
				            $products[$info['itemID']]['filename'] .
				            $products[$info['itemID']][$info['format']] .
				            '?id=' . $info['itemID'] . '&buyer=' . $userid;
				$filepath = filter_var($filepath, FILTER_SANITIZE_URL);

				$link = '<a href="' . $filepath . '">Download.</a>';
			} else {
				$filename = $products[$info['itemID']]['filename'] .
				            $products[$info['itemID']][trim($info['format'])];
				$filename = filter_var($filename, FILTER_SANITIZE_URL);

				$secureURL = NULL;
				$objectName = "/" . $filename;
				$secureURL = getS3Redirect($objectName, strtotime($info['time'])) . "\n";
				$secureURL = filter_var($secureURL, FILTER_SANITIZE_URL);
				$link = "<a href=\"$secureURL\">Download.</a>";
			}
		} else {
			$link = 'Download expired. Please contact <a href="mailto:' . htmlentities(BSDDS_SUPPORT_EMAIL) .
			        '">support</a> if you were unable to download your purchase.';

			if (DEBUG) {
				$link .= '(' . time() . ' < (' . strtotime($info['time']) . ' + ' . BSDDS_LINK_EXPIRY . '))';
			}
		}

		if ($info['status'] == "Pending" OR $info['currency'] != BSDDS_CURRENCY) {
			$link = "Waiting on purchase to complete.";
		}

		$format = str_replace(" ", "&nbsp;", htmlentities($info['format']));

		$type = NULL;
		if ($info['type']) {
			$type = "(" . htmlentities($info['type']) . ")";
		}

		$name = htmlentities($info['name']);
		$status = htmlentities($info['status']);

print <<<EOF
	<tr height="30" $which><td><strong>{$name}</strong> $type</td><td><span style='white-space: nowrap'>{$format}</span></td><td>{$status}</td><td><span style='white-space: nowrap'>$date</span></td><td>$link</td></tr>
EOF;

		$info = mysql_fetch_array($query);
	}

	echo "</table>";

	return TRUE;
}

function getS3Redirect($objectName, $time) {
	$objectName = str_replace(' ', '+', $objectName);

	$keyId = AMAZON_KEYID;
	$secretKey = AMAZON_SECRETKEY;
	$expires = $time + BSDDS_LINK_EXPIRY;
	$bucketName = AMAZON_BUCKETNAME;

	$stringToSign = "GET\n\n\n$expires\n$bucketName$objectName";

	# echo $stringToSign;

	$hasher =& new Crypt_HMAC($secretKey, "sha1");
	$sig = urlencode(hex2b64($hasher->hash($stringToSign)));

	return AMAZON_S3_URL. "$bucketName$objectName?AWSAccessKeyId=$keyId&Expires=$expires&Signature=$sig";
}

function hex2b64($str) {
	$raw = '';
	for ($i=0; $i < strlen($str); $i+=2) {
		$raw .= chr(hexdec(substr($str, $i, 2)));
	}
	return base64_encode($raw);
}

?>